<template>
    <div>
        <el-row type="flex" justify="space-between" align="middle">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>{{$t('exempt.baseInfo.noTrainingManagement')}}</el-breadcrumb-item>
                <el-breadcrumb-item>{{$t('exempt.baseInfo.applicationDetail')}}</el-breadcrumb-item>
            </el-breadcrumb>
            <el-button type="text" @click="handleClick('CANCEL')">返回</el-button>
        </el-row>
        <el-card>
            <el-row slot="header" type="flex" justify="space-between" align="center">
                <el-col span="2" style="font-size:18px;line-height:32px">
                    {{$t('exempt.baseInfo.courseForm')}}
                </el-col>
                <el-col span="2">
                    <el-button type="primary" @click="handleClick('CHOC')">{{$t('exempt.baseInfo.selectCourse')}}</el-button>
                </el-col>
            </el-row>
            <div style="color:red;margin-bottom: 10px;" v-if="aplForm.courseList.length !== 1">
                {{$t('exempt.baseInfo.caveat')}}
            </div>
            <el-form :model="aplForm" label-position="right" label-width="90px">
                <edu-table
                    :data="aplForm.courseList"
                    stripe
                    :selection="false"
                    style="width: 100%"
                    :pagination="false"
                    tooltip-effect="light"
                    @selection-change="selectionChange"
                >
                    <el-table-column :label="$t('label.classCode')" prop="classCode" />
                    <el-table-column :label="$t('label.courseCode')"  prop="courseCode" />
                    <el-table-column
                        :label="$t('label.courseName')"
                        prop="courseName"
                        min-width="120"
                        show-overflow-tooltip
                    />
                    <el-table-column :label="$t('label.openClassCollege')"  prop="collegeI18n" show-overflow-tooltip />
                    <el-table-column :label="$t('exempt.baseInfo.hours')"  prop="period" />
                    <el-table-column :label="$t('label.credits')" prop="credits" />
                    <el-table-column :label="$t('courseSummary.operation')" >
                        <template slot-scope="scope">
                            <el-button type="text" size="mini" @click="handleDelete(scope.$index)">
                                {{$t('message.delete')}}
                            </el-button>
                        </template>
                    </el-table-column>
                </edu-table>
                <el-form-item :label=" $t('exempt.baseInfo.applicationMode')+'：'" style="margin-top:16px">
                    <el-radio v-model="aplForm.applyType" label="0">{{$t('exempt.baseInfo.noTraining')}}</el-radio>
                    <el-radio v-model="aplForm.applyType" label="1">{{$t('exempt.baseInfo.noListening')}}</el-radio>
                </el-form-item>
                <el-form-item :label="$t('exempt.baseInfo.applicationInstructions')+'：'">
                    <el-input
                        type="textarea"
                        :rows="4"
                        :placeholder="$t('message.plsInput')"
                        v-model="aplForm.applyDesc"
                    ></el-input>
                </el-form-item>
                <el-form-item :label="$t('course.ProveMaterial')+'：'">
                    <el-upload
                        :headers="{
                            'X-Token': $store.state.session.sessionid
                        }"
                        :data="{
                            bucketname: 'face',
                            folderpath: 'file'
                        }"
                        limit="1"
                        action="/api/commonservice/obsfile/uploadfile"
                        :on-success="handlerSuccess"
                        :on-remove="handlerRemove"
                        :before-upload="beforeUpload"
                        :on-error="handlerError"
                        :on-exceed="handleExceed"
                        :file-list="aplForm.fileList"
                    >
                        <el-button size="small" type="primary">
                            <i class="el-icon-upload el-icon--left"></i>
                            {{$t('exempt.operation.upload')}}
                        </el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item style="text-align:end">
                    <el-button @click="handleClick('CANCEL')">{{$t('message.cancel')}}</el-button>
                    <el-button type="primary" @click="handleClick('CONFIRM')">
                        {{ aplForm.status == 2 || aplForm.status == 5 ? $t('exempt.operation.resubmit') : $t('message.confirm') }}
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card v-if="aplForm.status == 2 || aplForm.status == 5">
            <h1 slot="header" style="font-weight:bold">{{$t('exempt.baseInfo.reviewProgress')}}</h1>
            <edu-table
                stripe
                :pagination="false"
                :selection="false"
                style="width: 100%"
                tooltip-effect="light"
                :data="approveHistory"
            >
                <el-table-column :label="$t('message.time')" prop="approvalTime" />
                <el-table-column :label="$t('message.operator')" prop="reviewerName" />
                <el-table-column  :label="$t('message.department')" prop="roleI18N" />
                <el-table-column  :label="$t('label.operation')" prop="processOperateI18N" />
                <el-table-column :label="$t('exempt.baseInfo.explanation')" prop="reasonDesc" show-overflow-tooltip />
            </edu-table>
        </el-card>

        <edu-dialog
            :title="$t('exempt.baseInfo.chooseCourse')"
            :visible.sync="dialog.visible"
            width="75%"
            :before-close="handleClose"
        >
            <KeywordInputOne
                @enter="queryCourses(dialog.condition)"
                v-model="dialog.condition.courseCode"
                style="margin-bottom:16px"
                :placeholder="$t('exempt.baseInfo.searchCourseCode')"
            />
            <edu-table
                stripe
                style="width: 100%"
                tooltip-effect="light"
                :data="dialog.courseList"
                :total="dialog.condition.total_"
                :pageNum="dialog.condition.pageNum_"
                @page-change="handleCurrentChangeDialog"
                @selection-change="selectionChangeDialog"
            >
                <el-table-column  label="课程序号" prop="classCode" />
                <el-table-column  :label="$t('label.courseCode')" prop="courseCode" />
                <el-table-column
                    :label="$t('label.courseName')"
                    prop="courseName"
                    min-width="120"
                    show-overflow-tooltip
                />
                <el-table-column
                    :label="$t('label.openClassCollege')"
                    prop="collegeI18n"
                    min-width="100"
                    show-overflow-tooltip
                />
                <el-table-column :label="$t('exempt.baseInfo.hours')"  prop="period" />
                <el-table-column :label="$t('label.credits')" prop="credits" />
            </edu-table>
            <span slot="buttons">
                <el-button @click="dialog.visible = false">{{$t('message.cancel')}}</el-button>
                <el-button type="primary" @click="handleClick('DLGS')">{{$t('message.confirm')}}</el-button>
            </span>
        </edu-dialog>
    </div>
</template>
<script>
import { getSchedule, apply, exHistory, exSwitch} from 'common/src/api/exempt/exempt'
import UTILS from 'common/src/utils/utils'
import mixin from 'common/src/mixins/index';
export default {
    mixins: [mixin],
    data() {
        return {
            aplForm: {
                courseList: [],
                applyType: '1',
                applyDesc: '',
                fileList: [],
                attachFile: '',
                status: 0,
                workflowNo: ''
            },
            dialog: {
                visible: false,
                courseList: [],
                currentSelection: [],
                condition: {
                    studentId: '',
                    courseCode: '',
                    pageNum_: 1,
                    pageSize_: 20,
                    total_: 0
                }
            },
            approveHistory: []
        }
    },
    mounted() {
        this.dialog.condition.studentId = this.global.currentUser.uid
        let params = this.$route.query
        if (Object.keys(params).length > 0) {
            for (let key in params) {
                this.aplForm[key] = params[key]
            }
            this.getApproveList()
        }
    },
    methods: {
        handleClick(mode) {
            switch (mode) {
                //打开模态框
                case 'CHOC':
                    this.dialog.visible = true
                    this.$nextTick(()=>{
                        this.queryCourses();
                    });
                    break
                //模态框提交
                case 'DLGS':
                    this.dialog.visible = false
                    this.aplForm.courseList = _.cloneDeep(this.dialog.currentSelection)
                    this.dialog.courseList = []
                    this.dialog.currentSelection = []
                    break
                //申请取消
                case 'CANCEL':
                    this.$router.push({
                        path: '/EXLApplication'
                    });
                    this.$store.commit('delete_tabs', '/EXLApplicationDetail')
                    break
                //申请提交
                case 'CONFIRM':
                    if (this.aplForm.courseList.length !== 1){
                        this.$message({
                            type: 'warning',
                            message: '请检查课程门数'
                        })
                        return

                    }
                    exSwitch({
                        mode: '0'
                    }).then(res =>{
                        if (res.code == 200) {
                            let calendarId = res.data && res.data[0] && res.data[0].calendarId || '';
                            this.aplForm.courseList[0].calendarId = calendarId;
                            let params = {
                                studentId: this.dialog.condition.studentId,
                                applyType: this.aplForm.applyType,
                                applyDesc: this.aplForm.applyDesc,
                                attachFile: this.aplForm.fileList[0] && this.aplForm.fileList[0].url,
                                exemptCourseRel: this.aplForm.courseList[0],
                                faculty: this.global.currentUser.faculty || ''
                            }
                            this.requestApply(params)
                        }
                    })
                    break
            }
        },
        handleDelete(index) {
            this.aplForm.courseList.splice(index, 1)
        },
        async requestApply(params) {
            let { code, data } = await apply(params)
            if (code !== 200) return
            this.$message({
                type: 'success',
                message: '申请成功！'
            })
            this.handleClick('CANCEL');
        },
        async queryCourses(params = this.dialog.condition) {
            let { code, data } = await getSchedule(params)
            if (code !== 200) return
            this.dialog.courseList = data && data.list
            this.dialog.condition.pageNum_ = data.pageNum_
            this.dialog.condition.pageSize_ = data.pageSize_
            this.dialog.condition.total_ = data.total_
        },
        handleCurrentChangeDialog(val) {
            this.dialog.condition.pageNum_ = val.pageNum
            this.dialog.condition.pageSize_ = val.pageSize
            this.queryCourses()
        },
        selectionChangeDialog(val) {
            this.dialog.currentSelection = val
        },
        //移除文件回调
        handlerRemove(file, fileList) {
            this.aplForm.fileList = []
        },
        //上传文件成功回调
        handlerSuccess(response, file, fileList) {
            let responseCode = response.code
            if (responseCode === 200) {
                this.aplForm.fileList.push({
                    name: file && file.name,
                    url: file.response.data[file.name] && file.response.data[file.name].objectkey
                })
            } else {
                this.$message({
                    message: '文件列名错误或文件为空！',
                    type: 'error'
                })
            }
        },
        //文件超出个数限制
        handleExceed() {
            this.$message({
                message: '附件最多上传一个！',
                type: 'error'
            })
        },
        //上传文件失败回调
        handlerError(rresponse, file, fileList) {
            this.$message({
                message: '上传失败！',
                type: 'error'
            })
        },
        //上传文件类型校验
        beforeUpload(file) {
            return UTILS.checkFile(
                file,
                {
                    name: '.doc,.docx,.xls,.xlsx,.jpg,.bmp,.png,.pdf',
                    size: '0.5'
                },
                this
            )
        },
        async getApproveList() {
            let { code, data } = await exHistory(this.aplForm.workflowNo)
            if (code !== 200) return
            this.approveHistory = data
        }
    }
}
</script>